package com.ww.learn.coroutine.cancel

import com.ww.learn.coroutine.delay
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

// 打印结果
//job: I'm sleeping 0 ...
//job: I'm sleeping 1 ...
//job: I'm sleeping 2 ...
//job: I'm sleeping 3 ...
//main: I'm tired of waiting!
//job: I'm sleeping 4 ...
//main: Now I can quit.
fun main() = runBlocking {
    val job = launch (Dispatchers.Default) {
        repeat(5) { i ->
            try {
                println("job: I'm sleeping $i ...")
                delay(500L)
            } catch (e: Exception) {
                println("job: I'm exception: $e")
            }
        }
    }

    delay(1300L)
    println("main: I'm tired of waiting!")
    job.cancelAndJoin()
    println("main: Now I can quit.")
}